package lee.vioson.remotedata.manager

import android.content.Context
import androidx.datastore.preferences.core.edit
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import lee.vioson.remotedata.bean.CachedChapter
import lee.vioson.remotedata.bean.toJson
import lee.vioson.remotedata.bean.toObject

/**
 *Author:viosonlee
 *Date:2023/6/21
 *DESCRIPTION:
 */
object BookCacheManager {
    suspend fun cachedChapterInfo(
        context: Context,
        cachedChapter: CachedChapter
    ) {
        context.dataStore.edit {
            it[keyCachedBook(cachedChapter.bookId, cachedChapter.chapterId)] =
                cachedChapter.toJson()
        }
    }

    fun getCachedChapterInfo(context: Context, bookId: String, chapterId: String) = flow {
        val json = context.dataStore.data.map {
            it[keyCachedBook(bookId, chapterId)]
        }.firstOrNull()
        val cachedChapter = json?.toObject<CachedChapter>()
        emit(cachedChapter)
    }
}